package com.hspedu.newData.dmsxl.链表.遍历;

import com.hspedu.newData.dmsxl.ds.ListNode;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-04-27 
 * @Version: 1.0
 */

public class LC234回文链表 {

    // 将链表转成数组
    public boolean isPalindrome(ListNode head) {
        List<Integer> nums = new ArrayList<>();
        while(head != null){
            nums.add(head.val);
            head = head.next;
        }

        for (int i = 0,j = nums.size(); i < j; i++,j--) {
            if (nums.get(i) != nums.get(j)){
                return false;
            }
        }
        return true;
    }

    // todo 反转链表，对比里面的内容
    public boolean isPalindrome1(ListNode head) {
        ListNode node = new ListNode(0,head);
        ListNode listNode = reverse(head);
        node = node.next;
        while(node != null && listNode != null){
            if (node.val != listNode.val){
                return false;
            }
            node = node.next;
            listNode = listNode.next;
        }
        return node == listNode;
    }

    public ListNode reverse(ListNode head){

        ListNode dummy = null;
        ListNode cur = head;

        while (cur != null){
            ListNode temp = cur.next;
            cur.next = dummy;
            dummy = cur;
            cur = temp;
        }
        return dummy;
    }

    @Test
    public void test() {
        // 测试代码
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2,n1);
        ListNode n3 = new ListNode(2,n2);
        ListNode n4 = new ListNode(1,n3);

        boolean palindrome = isPalindrome1(n4);

        System.out.println("======");
    }
}
